package com.lh.oauth.impl;

import java.util.Date;

import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;

import org.springframework.stereotype.Component;

import com.lh.entity.OpenUser;
import com.lh.entity.OpenUser.OpenUserType;
import com.lh.oauth.OAuth;
import com.lh.util.HttpUtil;

/**
 * @author liuhui
 * @version 1.0
 * @date 2013-5-4 下午5:52:22
 */
@Component
public class BaiduOAuth implements OAuth {

	private static final String APP_KEY = "QUTtBSrYHAGdiS2yxG2MUZjD" ;
	private static final String SECRET_KEY = "7NL4uYDtZhk7dbIE2n0LoIuX3xRjtAB3" ;
	private static final String AUTHORIZE_URL = "https://openapi.baidu.com/oauth/2.0/authorize" ;
	private static final String TOKEN_URL = "https://openapi.baidu.com/oauth/2.0/token" ;
	private static final String USER_INFO_URL = "https://openapi.baidu.com/rest/2.0/passport/users/getLoggedInUser" ;

	
	@Override
	public String genLoginUrl() {
		StringBuilder queryString =  new StringBuilder();
		queryString.append("response_type=code&client_id=").append(APP_KEY).append("&redirect_uri=").append(CALLBACK_URL+"/" + OpenUserType.BAIDU.getValue()).append("&state=kaijingbao");
		return AUTHORIZE_URL + "?" + queryString.toString();
	}

	@Override
	public OpenUser obtainOpenUser(String code) {
		StringBuilder queryString =  new StringBuilder();
		queryString.append("grant_type=authorization_code&client_id=").append(APP_KEY).append("&client_secret=").append(SECRET_KEY).append("&code=").append(code).append("&redirect_uri=").append(CALLBACK_URL+"/" + OpenUserType.BAIDU.getValue());
		String accessTokenString = HttpUtil.get(TOKEN_URL + "?" +queryString.toString());
		
		JSONObject jsonObject = (JSONObject)JSONSerializer.toJSON(accessTokenString);
		String accessToken = jsonObject.getString("access_token");
		
		if(accessToken == null){
			return null;
		}
		String userInfoString = HttpUtil.get(USER_INFO_URL + "?access_token="+accessToken);
		JSONObject json = (JSONObject) JSONSerializer.toJSON(userInfoString);
		OpenUser ou = new OpenUser();
		ou.setCreateTime(new Date());
		ou.setNickname(json.getString("uname"));
		ou.setOpenid(json.getString("uid"));
		ou.setUserInfo(json.toString());
		ou.setType(OpenUserType.BAIDU.getValue());
		return ou ;
	}

	@Override
	public void shareInfo(OpenUser openUser) {
		
	}

}
